
#encoding:utf-8

from __future__ import absolute_import
import hashlib
import urllib2, urllib
import urllib
import json
import base64
from io import open

def md5str(unicode): #md5加密字符串
		m=hashlib.md5(unicode.encode(encoding = u"utf-8"))
		return m.hexdigest()
		
def md5(byte): #md5加密byte
		return hashlib.md5(byte).hexdigest()
		
class DamatuApi(object):	
	def __init__(self,username,password, ID, KEY, HOST):
		self.ID = ID
		self.KEY = KEY
		self.HOST = HOST
		self.username=username
		self.password=password
		
	def getSign(self,param=''):
		return (md5(str(self.KEY).encode("utf8") +str(self.username).encode("utf8") + param))[:8]
		
	def getPwd(self):
		return md5str(self.KEY +md5str(md5str(self.username) + md5str(self.password)))
		
	def post(self,path,params={}):
		data = urllib.urlencode(params).encode(u'utf-8')
		url = self.HOST + path
		response = urllib2.Request(url,data)
		return urllib2.urlopen(response).read()
	
	#查询余额 return 是正数为余额 如果为负数 则为错误码
	def getBalance(self):
		data={u'appID':self.ID,
			u'user':self.username,
			u'pwd':self.getPwd(),
			u'sign':self.getSign()
		}
		res = self.post(u'd2Balance',data)
		res = unicode(res, encoding = u"utf-8")
		jres = json.loads(res)
		if jres[u'ret'] == 0:
			return jres[u'balance']
		else:
			return jres[u'ret']
    
	#上传验证码 参数filePath 验证码图片路径 如d:/1.jpg type是类型，查看http://wiki.dama2.com/index.php?n=ApiDoc.Pricedesc  return 是答案为成功 如果为负数 则为错误码
	def decode(self,fdata,type):
# 		f=open(filePath,u'rb')
# 		fdata=f.read()
		filedata=base64.b64encode(fdata)
# 		f.close()
		data={u'appID':self.ID,
			u'user':self.username,
			u'pwd':self.getPwd(),
			u'type':type,
			u'fileDataBase64':filedata,
			u'sign':self.getSign(fdata)
		}		
		res = self.post(u'd2File',data)
		res = unicode(res, encoding = u"utf-8")
		jres = json.loads(res)
		if jres[u'ret'] == 0:
			#注意这个json里面有ret，id，result，cookie，根据自己的需要获取
			return(jres[u'result'])
		else:
			return jres[u'ret']
		
	#url地址打码 参数 url地址  type是类型(类型查看http://wiki.dama2.com/index.php?n=ApiDoc.Pricedesc) return 是答案为成功 如果为负数 则为错误码
	def decodeUrl(self,url,type):
		data={u'appID':self.ID,
			u'user':self.username,
			u'pwd':self.getPwd(),
			u'type':type,
			u'url':urllib.quote(url),
			u'sign':self.getSign(url.encode(encoding = u"utf-8"))
		}
		res = self.post(u'd2Url',data)
		res = unicode(res, encoding = u"utf-8")
		jres = json.loads(res)
		if jres[u'ret'] == 0:
			#注意这个json里面有ret，id，result，cookie，根据自己的需要获取
			return(jres[u'result'])
		else:
			return jres[u'ret']
	
	#报错 参数id(string类型)由上传打码函数的结果获得 return 0为成功 其他见错误码
	def reportError(self,id):
		#f=open('0349.bmp','rb')
		#fdata=f.read()
		#print(md5(fdata))
		data={u'appID':self.ID,
			u'user':self.username,
			u'pwd':self.getPwd(),
			u'id':id,
			u'sign':self.getSign(id.encode(encoding = u"utf-8"))
		}	
		res = self.post(u'd2ReportError',data)
		res = unicode(res, encoding = u"utf-8")
		jres = json.loads(res)
		return jres[u'ret']

		
#调用类型实例：
#1.实例化类型 参数是打码兔用户账号和密码	
#dmt=DamatuApi(u"test",u"test")
#2.调用方法：
#print dmt.getBalance() #查询余额 
#print dmt.decode(u'0349.bmp',200) #上传打码
#print dmt.decodeUrl(u'http://captcha.qq.com/getimage?aid=549000912&r=0.7257105156128585&uin=3056517021',200) #上传打码
#print(dmt.reportError('894657096')) #上报错误

